package com.macro.mall.portal.service.impl;

import com.macro.mall.mgb.mapper.ProductMapper;
import com.macro.mall.mgb.model.Member;
import com.macro.mall.mgb.model.Product;
import com.macro.mall.portal.domain.MemberReadHistory;
import com.macro.mall.portal.repository.MemberReadHistoryRepository;
import com.macro.mall.portal.service.MemberReadHistoryService;
import com.macro.mall.portal.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wangwang
 * @version 1.0
 * @description 会员浏览记录管理
 * @date 2025/8/2 9:41
 */
@Service
public class MemberReadHistoryServiceImpl implements MemberReadHistoryService {
    @Value("${mongo.insert.sqlEnable}")
    private Boolean sqlEnable;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private MemberReadHistoryRepository memberReadHistoryRepository;

    @Override
    public int create(MemberReadHistory memberReadHistory) {
        if(memberReadHistory.getProductId() == null){
            return 0;
        }
        Member member = memberService.getCurrentMember();
        memberReadHistory.setMemberId(member.getId());
        memberReadHistory.setMemberNickname(member.getNickname());
        memberReadHistory.setMemberIcon(member.getIcon());
        memberReadHistory.setId(null);
        memberReadHistory.setCreateTime(new Date());
        if(sqlEnable){
            Product product = productMapper.selectById(memberReadHistory.getProductId());
            if (product == null || product.getDeleteStatus() == 1) {
                return 0;
            }
            memberReadHistory.setProductName(product.getName());
            memberReadHistory.setProductSubTitle(product.getSubTitle());
            memberReadHistory.setProductPrice(product.getPrice() + "");
            memberReadHistory.setProductPic(product.getPic());
        }
        memberReadHistoryRepository.save(memberReadHistory);
        return 0;
    }

    @Override
    public int delete(List<String> ids) {
        memberReadHistoryRepository.deleteAllByIdIn(ids);
        return ids.size();
    }

    @Override
    public Page<MemberReadHistory> list(Integer pageNum, Integer pageSize) {
        Member member = memberService.getCurrentMember();
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        return  memberReadHistoryRepository.findByMemberId(member.getId(),pageRequest);
    }

    @Override
    public void clear() {
        Member member = memberService.getCurrentMember();
        memberReadHistoryRepository.deleteAllByMemberId(member.getId());
    }
}
